import time

from osv import osv, fields
from osv.orm import intersect
import netsvc

class kdvn_received(osv.osv):
    _description="KDVN Received"
    _name="kdvn.received"
    
    def _onchange_amount(self, cr, uid, ids,amount_tax,amount,actual_tax,actual_amount,rate=False):

        if rate:
            actual_tax=amount_tax*rate
            actual_amount=amount*rate
            val={'actual_total_amount':actual_tax+actual_amount,
                 'actual_tax_amount':actual_tax,
                 'actual_amount':actual_amount,
                 }
        else:            
            if actual_amount:
                if amount==0:
                    val={'rate':0}
                else:
                    tax_percent=amount_tax/amount
                    actual_tax=actual_amount*tax_percent
                    actual_total=actual_tax+actual_amount
                    rate=actual_total/(amount_tax+amount)
                    val={'actual_total_amount':actual_total,
                         'actual_tax_amount':actual_tax,
                         'rate':rate}
            elif actual_tax:
                actual_total=actual_tax+actual_amount
                rate=actual_total/(amount_tax+amount)
                val={'actual_total_amount':actual_total,
                     'rate':rate}
            else:
                if amount_tax+amount==0:
                    val={'total_amount':amount_tax+amount,
                     'rate':(actual_tax+actual_amount)/(amount_tax+amount)}
                else:
                    val={'total_amount':amount_tax+amount,
                     'rate':0}
        return {'value':val}
    
    def _get_currency(self,cr,uid,ids,name,arg,context={}):
        res = {}
        for kr in self.browse(cr, uid, ids):
            if kr.actual_claim_curr:
                res[kr.id]=kr.actual_claim_curr.id
            else:
                res[kr.id]=kr.payment_id.currency_id.id
        return res
    
    def _get_currency_from_kpfc(self,cr,uid,context={}):
        res = False
        if 'currency_id' in context:
            res = context['currency_id']
        return res

    def _get_amount_from_kpfc(self,cr,uid,context={}):
        claim_amount = False
        if 'claim_amount' in context:
            claim_amount = context['claim_amount']
        return claim_amount
    
    def _new_received(self, cr, uid, context={}):
        this_time=0
        if context:
            if 'claim_id' in context:
                if 'claim_amount' in context:
                    this_time=context['claim_amount']*context['exrate']
        return this_time

    def _new_received_total(self, cr, uid, context={}):
        this_time=0
        if context:
            if 'claim_id' in context:
                #pfc_obj=self.pool.get('kdvn.payment.from.client')
                kdvn_received_ids=self.search(cr,uid,[('payment_id','=',context['claim_id'])])
                received=0.0
                claim_amount=0.0
                amount_tax=0.0
                if 'amount_tax' in context:
                    amount_tax=context['amount_tax']
                if 'claim_amount' in context:
                    claim_amount=context['claim_amount']
                if kdvn_received_ids:
                    kdvn_received_lists=self.read(cr,uid,kdvn_received_ids,['amount','tax_amount'],context)
                    for krl in kdvn_received_lists:
                        received+=krl['amount'] + krl['tax_amount']
                this_time=claim_amount+amount_tax-received
        return this_time
    
    def _new_received_vat(self, cr, uid, context={}):
        this_time=0
        if context:
            if 'claim_id' in context:
                #pfc_obj=self.pool.get('kdvn.payment.from.client')
                kdvn_received_ids=self.search(cr,uid,[('payment_id','=',context['claim_id'])])
                received=0.0
                amount_tax=0.0
                if 'amount_tax' in context:
                    amount_tax=context['amount_tax']
                if kdvn_received_ids:
                    kdvn_received_lists=self.read(cr,uid,kdvn_received_ids,['tax_amount'],context)
                    for krl in kdvn_received_lists:
                        received+=krl['tax_amount']
                this_time=amount_tax-received
        return this_time

    def _get_currency_def(self, cr, uid, context={}):
        get_curr=False
        #try:
        cr.execute("Select get_default_currency()")
        for x in cr.fetchall():
            get_curr = x[0]
        return get_curr
    
    
    def _get_total(self,cr,uid,ids,name,arg,context={}):
        res={}
        for kr in self.browse(cr,uid,ids):
            if kr.actual_claim_amount:
                res[kr.id]=kr.actual_claim_amount
            else:
                res[kr.id]=kr.payment_id.kdvn_amount_total
        return res
    
    def _get_company_id(self,cr,uid):
        res = {}
        id = False
        for ru in pool.get('res.users').browse(cr,uid,[uid]):
            id=ru.company_id.partner_id.id
        return id
    
    _columns={
              'payment_id':fields.many2one('kdvn.payment.from.client','Payment ID'),
              'date':fields.date('Date'),
              'currency_id':fields.function(_get_currency,method=True,type="many2one",relation="kderp.currency",string="Claim Curr.",context={'typeofrate':'tax_office'}),
              'claim_amount':fields.function(_get_total,method=True,string='Claim Amount',type='float',digits=(16,2)),
              'actual_claim_amount':fields.float('Claim Amount'),
              'actual_claim_curr':fields.many2one('kderp.currency',"Claim Curr.",context={'typeofrate':'tax_office'}),
              'recv_cur':fields.many2one('kderp.currency','Recv. Cur.',required=True,context={'typeofrate':'tax_office'}),
              'recv_amount':fields.float('Recv. Amount',required=True),
              'bank_account_id':fields.many2one('res.partner.bank','Bank Account',domain=[('owner_name','ilike','%Kinden%Indo%')])
              }
    _defaults = {
                 'date':lambda *a:time.strftime('%Y-%m-%d'),
                 'actual_claim_amount':lambda *x:0.0,
                 'recv_amount':_new_received,
                 'recv_cur':_get_currency_def,
                 'currency_id':_get_currency_from_kpfc,
                 'claim_amount':_get_amount_from_kpfc
                 }
    
    def create(self, cr, uid, vals, context=None):
        payment_ids=[]
        if type(vals)==(type([])):
            for new_payment in vals:
                payment_ids.append(new_payment['payment_id'])
        else:
            payment_ids = [vals['payment_id']]
        new_ids = osv.osv.create(self, cr, uid,vals,context=context)

        total_received=0
        for kr in self.browse(cr, uid, new_ids).payment_id.received_ids:
            total_received+=kr.recv_amount if kr.recv_cur.code=='IDR' else kr.recv_amount*kr.payment_id.exchange_rate
            
        claim_amount=kr.payment_id.kdvn_amount_total*kr.payment_id.exchange_rate
        #raise osv.except_osv("E","%s-%s" % (total_received, claim_amount))
        if total_received!=claim_amount:
            return new_ids
        cr.commit()
        check_updated = False
        wf_service = netsvc.LocalService("workflow")
        if context:
            if '__last_update' in context:
                check_updated = True
                cr.execute("Update kdvn_payment_from_client set state='paid',write_uid=%d,write_date='%s' where id in (%s)" % (uid,time.strftime('%Y-%m-%d'),",".join(map(str,payment_ids))))
                for p_id in payment_ids:
                    wf_service.trg_delete(uid, 'kdvn.payment.from.client',p_id, cr)
        if not check_updated:
            for p_id in payment_ids:
                wf_service.trg_validate(uid, 'kdvn.payment.from.client', p_id,'action_to_done', cr)
        return new_ids
kdvn_received()


#class kdvn_contract_client(osv.osv):
#    _name = "kdvn.contract.client"
#    _description="KDVN Contract Client"
#    _inherit = "kdvn.contract.client"
#
#    def _compute_lines(self, cr, uid, ids, name, args, context=None):
#        mresult={}
#        for prj in ids:
#            mresult[prj]=[]
#            ids2 = self.search(cr, uid, [('parent_id', 'child_of', [prj])])
#            cr.execute("Select kr.id as payment_id \
#                            from account_invoice ai left join kdvn_received kr \
#                            on ai.id=kr.invoice_id where kr.id>0 and project_id in ("+ ','.join([str(x) for x in ids2]) + ')')
#            mresult[prj] = [x[0] for x in cr.fetchall()]
#        return mresult
#    
#    _columns = {
#                'payment_ids': fields.function(_compute_lines, method=True, relation='kdvn.received', type="one2many", string='Payments'),
#                }
#kdvn_contract_client()